<?php
/**
 * SetorService
 *
 * Acessa o Dao e o Repositorio do Setor e disponibiliza a outras
 * classes metodos (Servicos) que precisam.
 *
 */
class SetorService extends Model {

    /**
     * @var UsuarioDao
     */
    private $setorDao;
    /**
     * @var DepartamentoService
     */
    private $departamentoService;
    /**
     * @var UsuarioService
     */
    private $usuarioService;

    public function injectDependencies() {
        $this->setorDao = SetorDao::getInstance();
        $this->departamentoService = DepartamentoService::getInstance();
        $this->usuarioService = UsuarioService::getInstance();
    }

    public function findAll($AsSimple = false) {
        $ArSectors = $this->setorDao->findAll();
        if( !$AsSimple ) {
            $this->fillSector($ArSectors);
        }
        return $ArSectors;
    }

    //05-04
    public function findById($IDSetor) {
        $Setor = $this->setorDao->findById($IDSetor);
        $this->fillSector($Setor);
        return $Setor;
    }

    public function save($ArDados) {
        return $this->setorDao->save($ArDados);
    }

    //19-04-12
    public function update($ArDados) {
        $Sector = new Setor($ArDados['IDSetor'], $ArDados['IDDepartamento'], $ArDados['StSetor']);
        if( ! $this->setorDao->update($Sector) ) {
            return false;
        }
        if( $Sector->getIDSetor() == Dracosys::getLoggedUser()->getTDepartamento()->getSetores(true)->getIDSetor() ) {
            $this->usuarioService->reload();
        }
        return true;
    }

    //29-04
    public function delete($IDSetor) {
        if( ! $this->setorDao->delete($IDSetor) ) {
            return false;
        }
        if( $IDSetor == Dracosys::getLoggedUser()->getTDepartamento()->getSetores(true)->getIDSetor() ) {
            $this->usuarioService->reload();
        }
        return true;
    }

    //28/05
    public function changeDepartament($IDSetor, $IDNewDepartament) {
        return $this->setorDao->changeDepartament($IDSetor, $IDNewDepartament);
    }

    private function fillSector(&$MxSector) {
        if( !empty($MxSector) ) {
            $this->fillSectorWithDepartament($MxSector);
            $this->fillSectorWithEmployees($MxSector);
        }
    }

    private function fillSectorWithEmployees(&$MxSector) {
        if(!is_array($MxSector)) {
            $MxSector->loadEmployee();
            return;
        }
        foreach($MxSector as &$Setor) {
            $Setor->loadEmployee();
        }
    }

    //16-04
    public function fillSectorWithDepartament(&$MxSector) {
        if(!is_array($MxSector)) {
            $MxSector->setDepartamento($this->departamentoService->findById($MxSector->getIDDepartamento()));
            return;
        }
         foreach($MxSector as &$Setor) {
                $Setor->setDepartamento($this->departamentoService->findById($Setor->getIDDepartamento()));
        }
    }

}

?>
